package com.chenxin.springboot.config;


import com.chenxin.springboot.annotation.RepeatSubmit;
import com.chenxin.springboot.dto.BaseResponse;
import com.chenxin.springboot.dto.StatusCode;
import com.chenxin.springboot.util.CommonUtil;
import com.google.gson.Gson;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public abstract class RepeatSubmitInterceptor extends HandlerInterceptorAdapter {

    //开始拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod= (HandlerMethod) handler;
            Method method=handlerMethod.getMethod();
            RepeatSubmit submitAnnotation=method.getAnnotation(RepeatSubmit.class);
            if (submitAnnotation!=null){
                //如果是重复提交，则进行拦截，拒绝请求
                if (this.isRepeatSubmit(request)){
                    BaseResponse subResponse=new BaseResponse(StatusCode.CanNotRepeatSubmit);
                    CommonUtil.renderString(response,new Gson().toJson(subResponse));
                    return false;
                }
            }
            return true;
        }else{
            return super.preHandle(request, response, handler);
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    //自定义方法逻辑-判定是否重复提交
    public abstract boolean isRepeatSubmit(HttpServletRequest request);
}